package com.zyncro.remoting.rest;

import java.io.BufferedReader;
import java.io.InputStreamReader;

import javax.security.auth.login.LoginException;

import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.zyncro.remoting.rest.client.oauth.IOAuthAuthenticationHandler;

public class ZyncroAuthenticationHandler implements IOAuthAuthenticationHandler {
	private Log logger = LogFactory.getLog(getClass());

	private String authenticationURL;

	@Override
	public void doLogin(String username, String password, String requestToken) throws LoginException {
		HttpClient httpclient = new HttpClient();
		BufferedReader br = null;
		PostMethod post = null;
		try {
			post = new PostMethod(this.authenticationURL);

			// TODO check si es este token
			NameValuePair[] parameters = { new NameValuePair("username", username), new NameValuePair("password", password),
					new NameValuePair("request_token", requestToken) };

			post.setRequestBody(parameters);

			int returnCode = httpclient.executeMethod(post);
			logger.trace(String.format("HTTP Code: %1$s", returnCode));
			if (logger.isTraceEnabled()) {
				StringBuffer buffer = new StringBuffer();
				buffer.append("Headers: {");
				Header[] headers = post.getResponseHeaders();
				for (Header h : headers) {
					buffer.append("[").append(h.getName()).append(":").append(h.getValue()).append("];");
				}
				buffer.append("}");
				logger.trace(buffer.toString());
			}
			if (returnCode == HttpStatus.SC_OK) {
				br = new BufferedReader(new InputStreamReader(post.getResponseBodyAsStream()));
				String readLine;
				while (((readLine = br.readLine()) != null)) {
					logger.trace(readLine);
				}
			} else {
				throw new LoginException();
			}

		} catch (Exception e) {
			logger.equals(e);
		} finally {
			post.releaseConnection();
			if (br != null) {
				try {
					br.close();
				} catch (Exception fe) {
					logger.warn(fe);
				}
			}
		}
	}

	public String getAuthenticationURL() {
		return authenticationURL;
	}

	public void setAuthenticationURL(String authenticationURL) {
		this.authenticationURL = authenticationURL;
	}

}
